package com.wuercloud.http.server;

import com.wuercloud.config.ApplicationConfig;
import com.wuercloud.http.json.codec.HttpJsonRequestDecoder;
import com.wuercloud.http.json.codec.HttpJsonResponseEncoder;
import com.wuercloud.http.json.pojo.InfoObject;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

/**
 * Created by JiangWL on 2017/2/14.
 */
@Component
public class HttpJsonServer {

    private static Logger log = LoggerFactory.getLogger(HttpJsonServer.class);
    @Autowired
    private ServerBootstrap serverBootstrap;
    @Autowired
    private NioEventLoopGroup bossGroup;
    @Autowired
    private NioEventLoopGroup workerGroup;
    @Autowired
    private InetSocketAddress httpAddress;

    @Autowired
    private HttpJsonServerHandler jsonServerHandler;

    @PostConstruct
    public void run() throws Exception {

        /*bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup(4);*/
        try {
            /*ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)*/
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {


                @Override
                protected void initChannel(SocketChannel ch)
                        throws Exception {

                    //接收HttpJsonRequest，需要对应解码器
                    //ByteBuf->FullHttpRequest-> HttpJsonRequestDecoder
                    //输出HttpJsonResponse，需要对应编码器
                    //HttpResponseEncoder->FullHttpResponse-> HttpJsonResponseEncoder
                    ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                    ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                    ch.pipeline().addLast("json-decoder", new HttpJsonRequestDecoder(InfoObject.class));
                    ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                    ch.pipeline().addLast("json-encoder", new HttpJsonResponseEncoder());

                    //ch.pipeline().addLast("jsonServerHandler", new HttpJsonServerHandler());
                    ch.pipeline().addLast("jsonServerHandler", jsonServerHandler);
                }
            });
            ChannelFuture future = serverBootstrap.bind(httpAddress).sync();
            log.info("HTTP服务器已启动......");
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * 关闭http server
     */
    @PreDestroy
    public void shutdown() {
        if (this.bossGroup != null) bossGroup.shutdownGracefully();
        if (this.workerGroup != null) workerGroup.shutdownGracefully();
    }

    public static void main(String[] args) throws Exception {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
        HttpJsonServer httpJsonServer = (HttpJsonServer) context.getBean("httpJsonServer");
        //httpJsonServer.run();
        //context.close();
        context.registerShutdownHook();
        /*int port = 8080;
        if (args.length > 0) {
            try {
                port = Integer.parseInt(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        new HttpJsonServer(port).run();*/
    }
}
